<template>
	<div class="Body">
		<el-card shadow="always">
			<div class="scen-top">
				<img class="bigImg" :src="$store.state.imgShowRoad2 + '/file/' + currentImage" />
				<div class="minImg">
					<img class="img" v-for="(image, index) in smallImages" :key="index"
						:src="$store.state.imgShowRoad2 + '/file/' + image"
						:style="{ 'border': selectedIndex === index ? '2px solid blue' : '2px solid transparent' }"
						@click="changeImage(image,index)" />
				</div>
				<div class="title-top">
					<div class="spotName">{{ScenicSpotInfo.spotName}}</div>
					<div class="rate">
						<!-- pingfeng -->
					</div>
					<div class="baseInfoItem">
						<span class="baseInfoTitle">地址</span>
						<span class="baseInfoText">{{formattedSpotRegion}}{{ScenicSpotInfo.spotLocation}}</span>
					</div>
					<div class="baseInfoItem">
						<span class="baseInfoTitle">开放时间</span>
						<span class="baseInfoText">{{ScenicSpotInfo.openingHours}}</span>
					</div>
					<div class="baseInfoItem">
						<span class="baseInfoTitle">官方电话</span>
						<span class="baseInfoText">{{ScenicSpotInfo.spotNumber}}</span>
					</div>
					<div class="baseInfoItem">
						<span class="baseInfoTitle">公告信息</span>
						<span class="baseInfoDialog"
							@click="openDialog(ScenicSpotInfo.announcement)">{{ScenicSpotInfo.announcement}}</span>
					</div>
				</div>
			</div>

		</el-card>
		<el-card style="margin-top: 20px;width: 80%;" shadow="always">
			<div v-html="ScenicSpotInfo.spotIntroduce"></div>
		</el-card>
		<el-card style="margin-top: 20px;width: 80%;" shadow="always">
			<div class="evaluatebody">
				<div style="display: flex;justify-content: space-between;width: 100%;">
					<span
						style="font-family: PingFangSC-Medium;font-size: 20px;color: #333;line-height: 20px;font-weight: bold;">
						用户点评({{evaluateSum}})
					</span>
					<div>
						<el-button icon="el-icon-edit" size="mini" @click="openEvaluateDialog">写点评</el-button>
					</div>
				</div>
				<div style="display: flex;margin-top: 24px;align-items: center;">
					<span style="font-family: PingFangSC-Regular;font-size: 24px;">总评分：</span>
					<el-rate v-model="rateValue" :icon-classes="iconClasses" disabled
						void-icon-class="icon-rate-face-off" :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
					</el-rate>
					<span style="font-size: 24px;color: #0086f6;letter-spacing: 0;line-height: 24px;margin-left: 14px;">
						{{rateValue}}
					</span>
					<span>/5</span>
				</div>
				<div class="scen-evaluate" v-for="(item,index) in evaluateData" :key="index">
					<div class="user">
						<el-avatar :src="$store.state.imgShowRoad2 + '/file/'+item.avatar"></el-avatar>
						<span style="margin-left: 5px;">{{item.nickName}}</span>
					</div>
					<div class="evaluate-content">
						<div style="display: flex;justify-content: space-between;align-items: center;">
							<el-rate v-model="item.score" show-text :icon-classes="iconClasses" disabled
								void-icon-class="icon-rate-face-off" :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
							</el-rate>
							<div v-if = "$store.getters.gettoken == null"></div>
							<el-dropdown trigger="click" placement="bottom-end" v-else-if="item.username === userInfo.userName">
								<i class="el-icon-more" style="transform: rotate(90deg);"></i>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item @click.native="editMyEvalute(index,item)">编辑</el-dropdown-item>
									<el-dropdown-item @click.native="handleDelete(item.id)">删除</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>

						<div class="evaluateText">
							{{item.content}}
						</div>
						<div class="evaluate-ImgList">
							<div class="evaluate-Img" v-if="item.picture"
								v-for="(img,imgindex) in item.picture.split(',')" :key="imgindex">
								<el-image class="evaluate-elImg" :src="$store.state.imgShowRoad2 + '/file/'+ img"
									:preview-src-list="previewSrcList[index]">
								</el-image>
							</div>
						</div>
						<div class="evaluate-time">
							<span>{{item.createTime}}</span>
							<div class="tendency" @click="addEvaluateLike(item.id,item.linked)">
								<img :src="item.linked === true ? dainzan.hover : dainzan.default" alt="点赞" />
								<span :class="{ 'hover': item.linked === true }">{{item.likeCount}}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="page">
				<el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
					layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
			</div>
		</el-card>

		<el-dialog title="公告" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
			<span>{{announcement}}</span>
		</el-dialog>
		<el-dialog title="写点评" :visible.sync="dialogTableVisible" width="56%" :before-close="handleCloseEvaluate">
			<div style="display: flex;margin-bottom: 20px;">
				<span style="font-size: 16px; margin-right: 15px;width: 70px;">评分</span>
				<el-rate v-model="value" show-text :icon-classes="iconClasses" void-icon-class="icon-rate-face-off"
					:colors="['#99A9BF', '#F7BA2A', '#FF9900']" allow-half>
				</el-rate>
			</div>
			<div style="display: flex;margin-bottom: 20px;">
				<span style="font-size: 16px; margin-right: 15px;width: 70px;">上传图片
				</span>
				<el-upload class="orders-img_el_upload" :action="upurl" :limit="30" list-type="picture-card"
					:on-change="handleChange" :on-preview="handlePreview" :on-remove="handleRemove"
					:on-success="handleSuccess" :on-error="handleError" :file-list="fileList"
					:class="{ disUoloadSty: noneBtnImg }" multiple ref="upload">
					<span class="orders-img_el_upload_btn" @click.stop="submitUpload">添加图片(最多10张)</span>
				</el-upload>
			</div>
			<div style="display: flex;">
				<span style="font-size: 16px; margin-right: 15px;width: 70px;">评价内容
				</span>
				<el-input style="width: 95%;" type="textarea" maxlength="100" show-word-limit placeholder="请输入内容"
					v-model="evaluateContent" clearable>
				</el-input>
			</div>
			<el-dialog title="图片预览" :visible.sync="dialogVisibleImg" :modal="false" top="10vh" class="previewImg">
				<img v-if="dialogImageUrl" width="100%" :src="dialogImageUrl" alt="预览图片" />
			</el-dialog>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleCloseEvaluate">取 消</el-button>
				<el-button type="primary" @click="addEvaluate">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑点评" :visible.sync="EditdialogTableVisible" width="56%" :before-close="handleCloseEditEvaluate">
			<div style="display: flex;margin-bottom: 20px;">
				<span style="width: 60px;font-size: 16px; margin-right: 15px;">评分</span>
				<el-rate v-model="value" show-text :icon-classes="iconClasses" void-icon-class="icon-rate-face-off"
					:colors="['#99A9BF', '#F7BA2A', '#FF9900']" allow-half>
				</el-rate>
			</div>
			<div style="display: flex;margin-bottom: 20px;">
				<span style="font-size: 16px; margin-right: 15px;width: 100px;">上传图片
				</span>
				<el-upload class="orders-img_el_upload" :action="upurl" :limit="30" list-type="picture-card"
					:on-change="handleChange" :on-preview="handlePreview" :on-remove="handleRemove"
					:on-success="handleSuccess" :on-error="handleError" :file-list="fileList"
					:class="{ disUoloadSty: noneBtnImg }" multiple ref="upload">
					<span class="orders-img_el_upload_btn" @click.stop="submitUpload">添加图片(最多12张)</span>
				</el-upload>
			</div>
			<div style="display: flex;">
				<span style="font-size: 16px; margin-right: 15px;width: 70px;">评价内容
				</span>
				<el-input style="width: 95%;" type="textarea" maxlength="100" show-word-limit placeholder="请输入内容"
					v-model="evaluateContent" clearable>
				</el-input>
			</div>
			<el-dialog title="图片预览" :visible.sync="dialogVisibleImg" :modal="false" top="10vh" class="previewImg">
				<img v-if="dialogImageUrl" width="100%" :src="dialogImageUrl" alt="预览图片" />
			</el-dialog>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleCloseEditEvaluate">取 消</el-button>
				<el-button type="primary" @click="EditEvaluate">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import scenicApi from "@/api/scenicSpot.js"
	export default {
		data() {
			return {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				currentImage: "", // 当前显示的大图片
				smallImages: [], // 小图片列表
				ScenicSpotInfo: {},
				selectedIndex: 0,
				dialogVisible: false,
				dialogTableVisible: false,
				EditdialogTableVisible:false,
				dialogVisibleImg: false,
				uploadDisabled: false,
				dialogImageUrl: "",
				showBtnImg: true,
				noneBtnImg: false,
				limitCountImg: 30,
				upurl: "/api/file/upload/evaluate",
				fileList: [],
				announcement: "",
				value: null,
				iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'],
				dainzan: {
					default: require('../../assets/images/dianzan.png'),
					hover: require('../../assets/images/dianzan2.png')
				},
				evaluateData: [],
				evaluateSum: 0,
				evaluateContent: "", //评价内容
				evaluatePicture: "", //评价图片
				srcList: [], //评价图片集合
				rateValue: null,
				userInfo: {},
				evaluateId: null
			}
		},
		watch: {
			evaluateData: {
				handler(val) {
					// 当 farmEvaluate 数组发生变化时，将第一个对象的内容赋值给 value
					if (val.length > 0) {
						this.rateValue = val[0].averageMarks;
						this.evaluateSum = val[0].commentNumBer;
					}
				},
			}
		},
		computed: {
			formattedSpotRegion() {
				// 使用 replace 方法去掉逗号
				return this.ScenicSpotInfo.spotRegion ? this.ScenicSpotInfo.spotRegion.replace(/,/g, '') :
					''; // 将所有逗号替换为空字符串
			},
			previewSrcList() {
				// 将每个帖子的 contentCover 属性转换为数组
				return this.evaluateData.map(evaluate => {
					// 如果 contentCover 存在且是字符串类型，则将其按逗号分割成数组
					if (evaluate.picture && typeof evaluate.picture === 'string') {
						return evaluate.picture.split(',').map((image, index) => this.$store.state.imgShowRoad2 +
							'/file/' + image.trim());
					}
					// 否则返回空数组
					return [];
				});
			}
		},
		methods: {
			handleError(err, file, fileList) {
				this.$message({
					message: "上传失败！",
					type: "success",
				});
				console.log(err);
			},
			handleSuccess(response, file, fileList) {
				if (response.flag === true && response.data) {
					const newImagePath = response.data;
					if (!this.evaluatePicture) {
						this.evaluatePicture = newImagePath;
					} else {
						if (!this.evaluatePicture.includes(newImagePath)) {
							this.evaluatePicture += ',' + newImagePath;
						}
					}
			
					this.fileList = fileList;
					if (fileList.length >= 30) {
						this.uploadDisabled = true;
					}
					this.$message({
						message: "上传成功",
						type: "success",
					});
				} else {
					this.$message({
						message: "上传失败",
						type: "error",
					});
				}
			},
			handleChange(file, fileList) {
				this.noneBtnImg = fileList.length >= this.limitCountImg;
				this.fileList = fileList;
			},
			handleRemove(file, fileList) {
				if (fileList && fileList.length > 0) {
					this.updateHousePicture(fileList);
				} else if (fileList.length === 0) {
					this.evaluatePicture = '';
					this.fileList = [];
				}
			},
			updateHousePicture(fileList) {
				//使用了 new RegExp(pattern, flags) 来创建了一个正则表达式，其中 g 标志表示全局匹配
				this.evaluatePicture = fileList.map(file => file.url).join(',').replace(
					new RegExp(this.$store.state.imgShowRoad2 + '/file/', 'g'), ''
				);
				this.fileList = fileList;
			},
			handlePreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisibleImg = true;
			},
			submitUpload() {
				this.$refs.upload.submit();
			},
			handleCloseEvaluate() {
				this.dialogTableVisible = false;
				this.value = null;
				this.evaluatePicture = "";
				this.fileList = [];
				this.evaluateContent = "";
			},
			openEvaluateDialog() {
				if(this.$store.getters.gettoken == null){
					this.$message.warning('您还未登录！');
				}else{
					this.dialogTableVisible = true;
				}
				
			},
			editMyEvalute(index,item){
				this.EditdialogTableVisible=true;
				this.value = item.score;
				this.evaluatePicture = item.picture;
				this.fileList = item.picture.split(",").map((path, index) => ({
					uid: index,
					url: this.$store.state.imgShowRoad2 + '/file/'+path,
					name: `file-${index}`,
				}));
				this.evaluateContent = item.content;
				this.evaluateId = item.id;
			},
			handleCloseEditEvaluate(){
				this.EditdialogTableVisible=false;
				this.value = null;
				this.evaluatePicture = "";
				this.fileList = [];
				this.evaluateContent = "";
			},
			async EditEvaluate() {//修改评价
				let evaluateDate = {
					id: this.evaluateId,
					scenicId: this.getId(),
					content: this.evaluateContent,
					score: this.value,
					picture: this.evaluatePicture
				}
				const res = await scenicApi.editEvaluate("/znScenicEvaluate/editEvaluate", evaluateDate);
				if (res.code == 200) {
					this.selectEvaluate();
					this.EditdialogTableVisible = false;
					this.value = null;
					this.evaluatePicture = "";
					this.fileList = [];
					this.evaluateContent = "";
					this.$notify({
						title: '修改成功',
						type: "success",
						offset: 100
					});
				}else{
					this.selectEvaluate();
					this.EditdialogTableVisible = false;
					this.value = null;
					this.evaluatePicture = "";
					this.fileList = [];
					this.evaluateContent = "";
					this.$notify({
						title: '错误，请联系管理员',
						type: "success",
						offset: 100
					});
				}
			},
			async addEvaluate() {//新增评价
				let evaluateDate = {
					scenicId: this.getId(),
					content: this.evaluateContent,
					score: this.value,
					picture: this.evaluatePicture
				}
				const res = await scenicApi.addEvaluate("/znScenicEvaluate/addEvaluate", evaluateDate);
				if (res.code == 200) {
					this.selectEvaluate();
					this.dialogTableVisible = false;
					this.value = null;
					this.evaluatePicture = "";
					this.fileList = [];
					this.evaluateContent = "";
					this.$notify({
						title: '评价成功',
						type: "success",
						offset: 100
					});
				}
			},
			async searchScenicInfo() {
				const res = await scenicApi.searchScenicInfo('/znScenicspot/searchScenicInfo/' + this.getId());
				if (res.code === 200) {
					this.ScenicSpotInfo = res.data;
					this.processImages();
				}
			},
			async selectEvaluate() {
				if (this.$store.getters.gettoken == null) {
					const res = await scenicApi.selectNoLoginEvaluateAll(
						"/znScenicEvaluate/selectNoLoginEvaluateAll", {
							currentPage: this.currentPage,
							pageSize: this.pageSize,
							ScenicId: this.getId()
						});
					if (res.code == 200) {
						this.evaluateData = res.data.records;
						this.total = res.data.total;
					} else {
						this.$notify({
							title: '失败',
							message: '数据异常',
							type: "error",
							offset: 100
						});
					}
				} else {
					const res = await scenicApi.selectEvaluateAll("/znScenicEvaluate/selectEvaluateAll", {
						currentPage: this.currentPage,
						pageSize: this.pageSize,
						ScenicId: this.getId()
					});
					if (res.code == 200) {
						this.evaluateData = res.data.records;
						this.total = res.data.total;
					} else {
						this.$notify({
							title: '失败',
							message: '数据异常',
							type: "error",
							offset: 100
						});
					}
				}

			},
			async addEvaluateLike(evaluateid, linked) {
				// console.log(evaluateid)
				// console.log(linked)
				if (this.$store.getters.gettoken == null) {
					this.$message.error('您还未登录！');
				} else if(linked === false){
					let likeData = {
						evaluateId: evaluateid,
						likeStatus: linked === false ? 1 : 0
					}
					const res = await scenicApi.addEvaluateLike("/znScenicEvaluate/addEvaluateLike", likeData);
					if (res.code == 200) {
						this.$message.success("已点赞");
						this.selectEvaluate();
					} else {
						this.$message.warning("数据异常");
					}
				}else{
					let likeData = {
						evaluateId: evaluateid,
						likeStatus: linked === false ? 1 : 0
					}
					const res = await scenicApi.addEvaluateLike("/znScenicEvaluate/addEvaluateLike", likeData);
					if (res.code == 200) {
						this.$message.warning("取消点赞");
						this.selectEvaluate();
					} else {
						this.$message.warning("数据异常");
					}
				}
			},
			handleDelete(id) { //删除点击事件
				this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.DelMyEvalute(id),
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			async DelMyEvalute(id){
				const res = await scenicApi.delEvaluate("/znScenicEvaluate/delEvaluate/" + id);
				this.selectEvaluate();
			},
			processImages() {
				if (this.ScenicSpotInfo.spotPicture && this.ScenicSpotInfo.spotPicture.length > 0) {
					this.currentImage = this.ScenicSpotInfo.spotPicture.split(',')[0];
					this.smallImages = this.ScenicSpotInfo.spotPicture.split(',');
				}
			},
			changeImage(image, index) {
				// 点击小图片时切换大图片
				this.currentImage = image;
				this.selectedIndex = index;
			},
			openDialog(announcement) {
				this.announcement = announcement;
				this.dialogVisible = true;
			},
			handleClose() {
				this.dialogVisible = false;
			},
			getId() {
				return this.$route.params.spotId;
			},
			handleCurrentChange(page) {
				this.currentPage = page;
				this.selectEvaluate();
			},
		},
		mounted() {
			const spotId = this.getId();
			console.log("获取到的ID为：", spotId);
		},
		created() {
			this.searchScenicInfo();
			this.selectEvaluate();
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
		}
	}
</script>

<style lang="scss" scoped>
	.Body {
		margin: 10px 15% 0 15%;

		.scen-top {
			display: flex;

			.bigImg {
				width: 536px;
				height: 424px;
				background-size: 100% 100%;
				margin-right: 10px;
			}

			.minImg {
				display: flex;
				flex-direction: column;

				.img {
					margin-bottom: 6px;
					width: 128px;
					height: 98px;
					background-size: 100% 100%;
					cursor: pointer;
				}

			}

			.title-top {
				-webkit-box-flex: 1;
				-ms-flex: 1;
				flex: 1;
				margin-left: 20px;
				overflow: hidden;
				position: relative;

				.spotName {
					display: inline;
					font-size: 30px;
					color: #333;
					line-height: 40px;
					vertical-align: middle;
				}

				.rate {
					margin-bottom: 80px;
				}

				.baseInfoItem {
					display: flex;
					height: 20px;
					-webkit-box-align: center;
					align-items: center;
					margin-bottom: 26px;

					.baseInfoTitle {
						width: 64px;
						-ms-flex-negative: 0;
						flex-shrink: 0;
						font-weight: bold;
						font-size: 14px;
						line-height: 20px;
						color: #333;
					}

					.baseInfoText {
						-ms-flex-negative: 1;
						flex-shrink: 1;
						font-size: 14px;
						line-height: 20px;
						color: #333;
						margin-left: 8px;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}

					.baseInfoDialog {
						color: #f85e53;
						cursor: pointer;
						-ms-flex-negative: 1;
						flex-shrink: 1;
						font-size: 14px;
						line-height: 20px;
						margin-left: 8px;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
			}
		}

		.evaluatebody {
			width: 100%;
			display: flex;
			flex-direction: column;

			.scen-evaluate {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				padding: 25px 0;

				.user {
					font-family: PingFangSC-Regular;
					font-size: 14px;
					color: #646464;
					letter-spacing: 0;
					display: flex;
					align-items: center;
				}

				.evaluate-content {
					display: flex;
					flex-direction: column;
					position: relative;
					width: calc(100% - 160px);
					border-bottom: 1px solid #f5f5f5;

					.evaluateText {
						margin-top: 20px;
						font-family: PingFangSC-Regular;
						font-size: 16px;
						// line-height: 16px;
					}

					.evaluate-time {
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: space-between;
						margin-bottom: 6px;

						span {
							font-family: PingFangSC-Regular;
							font-size: 14px;
							color: #999;
						}

						.tendency {
							display: flex;
							flex-direction: row;
							align-items: center;
							justify-content: space-between;

							img {
								width: 20px;
							}
						}
					}

					.evaluate-ImgList {
						margin-top: 16px;
						display: flex;
						flex-wrap: wrap;

						.evaluate-Img {
							width: 120px;
							height: 120px;
							margin-right: 12px;
							margin-bottom: 12px;

							.evaluate-elImg {
								width: 100%;
								height: 100%;
								border: 0;
								margin: 0;
								padding: 0;
								vertical-align: top;

							}

						}

					}
				}

			}

		}

		.page {
			display: flex;
			justify-content: center;
		}

		.hover {

			color: #ff8200;
		}
	}
</style>